package cn.yh.springsecurity.utils;

import cn.yh.springsecurity.domain.entity.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

public class JWTUtils {
    public static final String TOKEN_SECRET = "QSsdfaASvVaCAzxG";


    public static String createToken(User user){

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 30); // 设置过期时间为30天

        return JWT.create().withAudience(String.valueOf(user.getUserId()))
                .withClaim("userId", user.getUserId())
                .withClaim("username", user.getUserName())
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(JWTUtils.TOKEN_SECRET));
    }

    /** 从请求头中获取token中的userId
     * @return userId
     * */
    public static Long getUserIdByAudience(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        return Long.valueOf(JWT.decode(token).getAudience().get(0));
    }

    /** 从请求头中获取token中的userId
     * @return userId
     * */
    public static Long getUserIdByClaim(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        return JWT.decode(token).getClaim("userId").asLong();  //获取token中的userId
    }
    /*新增方法
    *
    * */
//    public static Long getUserIdByToken(String token){
//        return JWT.decode(token).getClaim("userId").asLong();  //获取token中的userId
//    }
    /**
     * 从请求属性对象中获取请求对象
     * @return request对象
     */
    public static HttpServletRequest getRequest(){
        RequestAttributes requestAttributes = getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        return servletRequestAttributes.getRequest();
    }

    /** 获取token中的username
     * @return username
     * */
    public static String getUsernameByClaim(){
        HttpServletRequest request = getRequest();
        String token = request.getHeader("token");
        return JWT.decode(token).getClaim("username").asString();  //获取token中的username
    }
    /*
    * 从线程服务中获取request对象
    * @return request对象
    * */
    public static RequestAttributes getRequestAttributes(){
        return RequestContextHolder.getRequestAttributes();
    }
}

